package Cantella::DJabberd::Store::Result::RosterGroup;

use base qw/DBIx::Class::Core/;
use metaclass 'Reaction::Meta::Class';
use Moose;

use MooseX::Types::Moose qw/ArrayRef Int/;
use Reaction::Types::Core qw/NonEmptySimpleStr/;

use aliased 'Cantella::DJabberd::Store::Result::UserJid';
use aliased 'Cantella::DJabberd::Store::Result::RosterGroupItem' => 'GroupItem';

use namespace::clean -except => [ 'meta' ];

has id           => (is => 'ro', required => 1, isa => Int );
has owner        => (is => 'rw', required => 1, isa => UserJid );
has name         => (is => 'rw', required => 1, isa => NonEmptySimpleStr );
has roster_items => (
                      isa => ArrayRef,
                      reader => 'get_roster_items',
                      writer => 'set_roster_items'
                     );

{
  no warnings 'redefine';
  *get_roster_items = sub { [ shift->roster_items->all ] };
}

__PACKAGE__->table('roster_groups');
__PACKAGE__->add_columns
  (
   id       => {
                data_type => "INT",
                size => 10,
                default_value => undef,
                is_nullable => 0,
                is_auto_increment => 1,
                extra => { unsigned => 1 },
               },
   owner_id => {
                 data_type => "INT",
                 size => 10,
                 is_nullable => 0,
                 is_foreign_key => 1,
                 extra => { unsigned => 1 },
               },
   name     => {
                data_type => "VARCHAR",
                size => 255,
                default_value => "",
                is_nullable => 0,
               },
  );

__PACKAGE__->set_primary_key('id');
__PACKAGE__->add_unique_constraint(owner_name => [qw/owner_id name/]);

__PACKAGE__->belongs_to(owner => UserJid, { id => 'owner_id' });

__PACKAGE__->has_many(
                      roster_group_items => GroupItem, 
                      {'foreign.roster_group_id' => 'self.id'}
                     );
__PACKAGE__->many_to_many(roster_items => 'roster_group_items', 'roster_item');

sub display_name { shift->name }

__PACKAGE__->meta->make_immutable(inline_constructor => 0);

1;
